package com.sinosoft.sm.system.web;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sinosoft.sm.system.common.exception.ObjectIsNotExistedException;
import com.sinosoft.sm.system.common.utils.StringUtil;
import com.sinosoft.sm.system.common.utils.ajax.ResponseData;
import com.sinosoft.sm.system.resource.dto.ResourceData;
import com.sinosoft.sm.system.resource.entity.ResourceEntity;
import com.sinosoft.sm.system.resource.service.api.ResourceService;
import com.sinosoft.sm.system.role.dto.UserRoleRefData;
import com.sinosoft.sm.system.role.entity.RoleEntity;
import com.sinosoft.sm.system.role.entity.UserRoleRefEntity;
import com.sinosoft.sm.system.role.service.api.RoleService;
import com.sinosoft.sm.system.security.SecurityUtil;
import com.sinosoft.sm.system.web.dto.AppUserData;
import com.sinosoft.sm.user.entity.UserEntity;
import com.sinosoft.sm.user.service.api.UserService;
import com.sinosoft.sm.user.web.dto.UserData;


/**
 * 系统资源加载控制层
 * @author leichao
 *
 */
@Controller
@RequestMapping("system")
public class SMController {


	@Autowired
	private UserService userService;
	
	@Autowired
    private ResourceService resourceService;
	
	@Autowired
	private RoleService roleService;
	
	
	/**
	 * 获取用户帐号服务
	 * @return	回执数据
	 */
	@RequestMapping(value="/getUsernameService", method = RequestMethod.POST)
	@ResponseBody
	public String getLoginName(){
		return SecurityUtil.getUsername();
	}
	
	/**
	 * 获取应用上下文中的用户信息
	 * @param aid
	 * @param username
	 * @return
	 */
	@RequestMapping(value="/getAppUserDataService", method=RequestMethod.POST)
	@ResponseBody
	public ResponseData getUserDataService(String aid, String username){
		if(StringUtil.isBlank(username)) {
			return new ResponseData(false, null, "PmsController:getUserDataService调用失败，参数不能为空", null);
		}
		UserEntity userEntity = null;
		try {
			userEntity = userService.getUserByUsername( username);
		} catch (ObjectIsNotExistedException e) {
			// TODO Auto-generated catch block
			return new ResponseData(false, null,"用户不存在",null);
		}
		if(userEntity == null){
			return new ResponseData(false, null,"用户信息不在",null);
		}
		List<UserRoleRefEntity> roleUserRefs = roleService.getRolesByUser(username);
		if(roleUserRefs == null || roleUserRefs.size() == 0){
			return new ResponseData(false, null,"角色集合信息不存在",null);
		}
		AppUserData appUserData = new AppUserData(getUserData(userEntity),getRoleUserRefDatas(roleUserRefs));
		ResponseData response = new ResponseData(true,appUserData);
		return response;
	}
	
	
	/**
	 * 获取某角色的应用权限信息
	 * @param roleids	角色编号集合
	 * @param aid	应用编号
	 * @return 回执数据
	 */
	@RequestMapping(value="/getAppPermissionDataService",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData getAppPermissionDataService(@RequestParam("roleids[]")String[] roleIds,String aid){
		if(roleIds.length==0) {
			return new ResponseData(false, null, "参数：角色编号集合不能为空", null);
		}
		List<ResourceEntity> entityList = resourceService.getPermissionsByRoles(roleIds);
		if(entityList.size()<=0){
			return new ResponseData(false, null,"该用户的角色为分配该应用的资源权限信息不在",null);
		}else{
			/*List<ResourceData> datalist = getResourceDatas(entityList);
			List<ResourceData> resourcedata = new ArrayList<ResourceData> ();
			for(int i=0;i<datalist.size();i++) {
				String id = datalist.get(i).getId();
				String pid = datalist.get(i).getPid();
				if(StringUtil.isBlank(pid)) {
					ResourceData data = getChildrenListById(datalist,id,datalist.get(i));
					resourcedata.add(data);
				}
			}*/
			return new ResponseData(true,entityList);
		}
	}
	//递归查询父子节点关系
	private ResourceData getChildrenListById(List<ResourceData> list,String id,ResourceData resourceData){
		List<ResourceData> resourcelist = new ArrayList<ResourceData>();
		for(int i=0;i<list.size();i++){
			String pid = list.get(i).getPid();
			if(id.equals(pid)){
				resourcelist.add(list.get(i));
				getChildrenListById(list,list.get(i).getId(),list.get(i));
			}
			resourceData.setChildren(resourcelist);
		}
		return resourceData;
		
	}
	
	/**
	 * 获取某角色的应用权限信息
	 * @param roleids	角色编号集合
	 * @param aid	应用编号
	 * @return 回执数据
	 */
	@RequestMapping(value="getAppPermissionDataByRoleIdService",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData getAppPermissionDataByRoleIdService(String roleid,String aid){
		if(StringUtil.isBlank(roleid)) {
			return new ResponseData(false, null, "参数：角色编号不能为空", null);
		}
		List<ResourceEntity> entityList = resourceService.getResourceByRoleId(roleid);
		if(entityList.size()<=0){
			return new ResponseData(false, null,"该用户的角色为分配该应用的资源权限信息不在",null);
		}else{
			List<ResourceData> datalist = getResourceDatas(entityList);
			List<ResourceData> resourcedata = new ArrayList<ResourceData> ();
			for(int i=0;i<datalist.size();i++) {
				String id = datalist.get(i).getId();
				String pid = datalist.get(i).getPid();
				if(StringUtil.isBlank(pid)) {
					ResourceData data = getChildrenListById(datalist,id,datalist.get(i));
					resourcedata.add(data);
				}
			}
			return new ResponseData(true,resourcedata);
		}
	}
	
	
    
    /**
     * 获取应用的角色类型
     * @param aid
     * @return 角色类型集合
     */
    @RequestMapping(value="/getRolesDataService",method=RequestMethod.POST)
    @ResponseBody
    public ResponseData getRolesDataService( String aid,String status){
    	if(StringUtil.isBlank(aid)) {
			return new ResponseData(false, null,"参数：应用编号不能为空",null);
		}
    	List<RoleEntity> result = roleService.getAllRoles();
    	return new ResponseData(true,result);
    }
	
    
	
	/**
	 * 获取用户传输数据
	 * 将实体数据转换为传输数据集合
	 * @param users	用户实体数据集合
	 * @return	用户传输数据集合
	 */
	private UserData getUserData(UserEntity user) {
		UserData userData = new UserData();
		userData.toUserData(user);
		return userData;
	}
	
	/**
	 * 获取角色用户关系传输数据
	 * @param roleUserRefs	角色用户关系实体集合
	 * @return	角色用户关系传输数据集合
	 */
	private List<UserRoleRefData> getRoleUserRefDatas(List<UserRoleRefEntity> roleUserRefs) {
		int size = roleUserRefs.size();
		List<UserRoleRefData> roleUserRefDatas = new ArrayList<UserRoleRefData> ();
		for(int i=0; i<size; i++) {	//	循环将实体数据转换为传输数据
			UserRoleRefData roleUserRefData = new UserRoleRefData();
			roleUserRefData.toUserRoleRefData(roleUserRefs.get(i));
			roleUserRefDatas.add(roleUserRefData);
		}
		return roleUserRefDatas;
	}
	
	/**
	 * 获取应用的权限信息
	 * @param permissionEntitys	权限实体集合
	 * @return	权限传输数据集合
	 */
	private List<ResourceData> getResourceDatas(List<ResourceEntity> entitys) {
		int size = entitys.size();
		List<ResourceData> resourceDatas = new ArrayList<ResourceData> ();
		for(int i=0; i<size; i++) {	//	循环将实体数据转换为传输数据
			ResourceData resourceData = new ResourceData();
			resourceData.toResourceData(entitys.get(i));
			resourceDatas.add(resourceData);
		}
		return resourceDatas;
	}
	
	
	/**
	 * 用户密码校验
	 * 若捕获异常ObjectIsNotExistedException，则返回异常消息
	 * @param aid	应用编号
	 * @param username	用户帐号
	 * @param password	密码
	 * @return	回执数据
	 */
	@RequestMapping(value="checkUserPasswordService", method=RequestMethod.POST)
	@ResponseBody
	public ResponseData checkUserPassword(String aid, String username, String password) {
		try {
			boolean result = userService.checkUserPassword(username, password);
			return new ResponseData(result, null);
		} catch (ObjectIsNotExistedException e) {
			return new ResponseData(false, null, e.getMessage(), null);
		}
	}
	
	/**
	 * 更新用户密码
	 * 若捕获异常ObjectIsNotExistedException，则返回异常消息
	 * @param aid	应用编号
	 * @param username	用户帐号
	 * @param oldPassword	旧密码
	 * @param newPassword	新密码
	 * @return	回执数据
	 */
	@RequestMapping(value="updateUserPasswordService", method=RequestMethod.POST)
	@ResponseBody
	public ResponseData updateUserPassword(String aid, String username, String oldPassword, String newPassword) {
		try {
			boolean result = userService.checkUserPassword(username, oldPassword);
			if(result == false) {
				return new ResponseData(false, null, "用户密码不匹配", null);
			} else {
				return new ResponseData(userService.updateUserPassword(username, newPassword), null);
			}
		} catch (ObjectIsNotExistedException e) {
			return new ResponseData(false, null, e.getErrorMsg(), null);
		}
	}
}
